package com.hk.core.authentication.security.authentication.email;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.ArrayList;
import java.util.Objects;

/**
 * 邮箱验证 Provider
 *
 * @author kevin
 * @date 2018-07-26 16:41
 */
public record EmailAuthenticationProvider(boolean needBindAccount,
                                          UserDetailsService userDetailsService) implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        var token = (EmailAuthenticationToken) authentication;
        var userDetails = userDetailsService.loadUserByUsername(token.getPrincipal().toString());
        if (needBindAccount && Objects.isNull(userDetails)) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        var authorities = Objects.isNull(userDetails) ?
                new ArrayList<GrantedAuthority>(0) : userDetails.getAuthorities();
        var authenticationToken = new EmailAuthenticationToken(token.getPrincipal(), authorities);
        authenticationToken.setDetails(token.getDetails());
        return authenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return EmailAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
